from lib.config.index import log_config
from lib.clock import rtc_clock
from utils import file
import os
import sys


class Logger:
    def __init__(self) -> None:
        self.__root = log_config.get_root()
        self.__path = "/all.log"
        self.__name = "base log"
        self.__rtc = rtc_clock.clock
        self.init_root()

    def init_root(self):
        if not file.is_dir(self.__root):
            os.mkdir(self.__root)

    def get_log_path(self):
        return f"{self.__root}{self.__path}"

    def log(self, *args):
        raise Exception("log should implement by children!")

    def clean(self):
        """清理日志"""
        log_path = self.get_log_path()

        if not file.is_file(log_path):
            return

        try:
            os.remove(log_path)
        except Exception as e:
            sys.print_exception(e)

    def write(self, msg):
        output = log_config.get_output()

        # 未开启日志
        if not log_config.is_enable():
            return

        datetime = self.__rtc.get_datetime()
        msg = f"{datetime}: {msg}"
        if output == "file":
            self.write_file(msg)
        if output == "repl":
            self.write_repl(msg)

    def write_file(self, msg):
        try:
            with open(self.get_log_path(), "a+") as f:
                f.write(msg)
        except Exception as e:
            pass

    def write_repl(self, msg):
        print(f"{self.__name}: {msg}")
